﻿var viewModel = new function () {
	this.ColName = ko.observable("Email");
	this.SortOrder = ko.observable("desc");

	this.dataEmailOptOutList = ko.observableArray(data.EmailOptOutReportInfo || []);
	// No Results Found!
	this.NoResultsFound = ko.computed(function() {
		return (!this.dataEmailOptOutList() || !this.dataEmailOptOutList().length);
	}, this);
	this.NotFoundMessage = ko.observable("No results were found.");

	this.PageSize = ko.observable(10);
	this.CurrentPageIndex = ko.observable(1);
	this.MaxPageIndex = ko.computed(function () {
		return Math.ceil(ko.utils.unwrapObservable(this.dataEmailOptOutList().length / this.PageSize()));
	}, this);
	// Define varials to handle filter section
	this.FilterOption = ko.observable("true");
	this.FromDateEnable = ko.computed(function () {
		if (this.FilterOption() == "true")
			return true;

		return;
	}, this);
	this.SearchEnable = ko.computed(function () {
		if (this.FilterOption() == "false")
			return true;
		return;
	}, this);
	this.ToDateEnable = ko.computed(function () {
		if (this.FilterOption() == "true")
			return true;

		return;
	}, this);

	// PageSize/ PageCurrent keypress enter
	this.RunSomethingKey = function (viewModel, event) {
		if (event.keyCode == 13) {
			this.RunSomething(viewModel, event);
		}
		return true;
	}
	this.RunSomething = function (viewModel, event) {
		searchforOptOutReport();
	}

	this.txtSearch = ko.observable("");
	this.search = function () {
		searchforOptOutReport();
	}
	function searchforOptOutReport() {
		var searchString = $.trim($('#txtSearchText').val());

		var dataPost = {
			"filterDate": viewModel.FilterOption(),
			"startDate": $('#startDate').val(),
			"endDate": $('#endDate').val(),
			"email": searchString
		};

		// Ajax loading
		$("#visibleErrormsg").hide();
		viewModel.NotFoundMessage("No results were found.");
		openProcess();

		var urlPost = "/EmailOptOutReport/EmailOptOutReport";
		$.ajax({
			type: "POST",
			url: urlPost,
			data: dataPost,
			dataType: "json",
			success: function (returnData, textStatus, jqXHR) {
				hideProcess();

				// Check for no results
				if (typeof returnData != "undefined" && (typeof returnData.Error == "undefined" || !returnData.Error)) {
					//if (viewModel.FilterOption() == "false")
					//	viewModel.NotFoundMessage('No results were found for "' + searchString + '".');

					viewModel.dataEmailOptOutList(returnData);
					viewModel.CurrentPageIndex(1);

					ClearSortImage();
				}
				else {
					//if (viewModel.FilterOption() == "false")
					//	viewModel.NotFoundMessage('No results were found for "' + searchString + '".');

					viewModel.dataEmailOptOutList([]);
					$("#visibleErrormsg").show();
				}
			},
			error: function (xhr, status, error) {
				hideProcess();

				viewModel.dataEmailOptOutList([]);
				showPopupError();
			}
		}); // End ajax post
		return false;
	}
	this.OptoutReport = ko.computed(function () {

		var pagevalue = this.PageSize().toString().replace(/\s/g, '');
		var pagesize = parseInt(pagevalue, 10);

		if (pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
			return "";
		}
		else {
			var startIndex = this.PageSize() * (this.CurrentPageIndex() - 1);
			var endIndex = parseInt(startIndex) + parseInt(this.PageSize());

			return this.dataEmailOptOutList.slice(startIndex, endIndex);
		}
	}, this);

	////////////////////////////// PAGING /////////////////////////////////////
	this.PageSizeText = ko.computed(function () {
		if (this.dataEmailOptOutList().length > 0) {
			var pagevalue = this.PageSize().toString().replace(/\s/g, '');
			var pagesize = parseInt(pagevalue, 10);
			this.CurrentPageIndex(1);
			//alert(pagesize);
			if (!IsNumeric(pagevalue))
				return "* Please enter a number between 1 - 100";
			else if (pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
				return "* Please enter a number between 1 - 100";
			}
			else {
				return "";
			}
		}

	}, this);
	this.PageCurrentText = ko.computed(function () {
		if (this.dataEmailOptOutList().length > 0) {
			var pagevalue = this.CurrentPageIndex().toString().replace(/\s/g, '');
			var pageindex = parseInt(pagevalue, 10);
			if (!IsNumeric(this.CurrentPageIndex()) || pagevalue == "")
				return "* Please enter a number between 1 - " + this.MaxPageIndex() + " ";
			else if (pagevalue.toString() == 'NaN' || !IsNumeric(pagevalue) || pageindex < 1 || pageindex > this.MaxPageIndex()) {
				return "* Please enter a number between 1 - " + this.MaxPageIndex() + " ";
			}
			else {
				return "";
			}
		}
		else {
			return "";
		}

	}, this);

	this.PrevPage = function () {
		var page = parseInt(this.CurrentPageIndex());
		if (page > 1) {
			this.CurrentPageIndex(page - 1);
		}
	}
	this.PrevButtonClass = ko.computed(function () {
		var page = parseInt(this.CurrentPageIndex());
		if (page > 1) {
			return "btn btn-prev-arrow prev-active";
		}
		else {
			return "btn btn-prev-arrow";
		}
	}, this);

	this.NextPage = function () {
		var page = parseInt(this.CurrentPageIndex());
		if (page < this.MaxPageIndex()) {
			this.CurrentPageIndex(page + 1);
		}
	}

	this.NextButtonClass = ko.computed(function () {
		if (this.CurrentPageIndex() == this.MaxPageIndex() || this.MaxPageIndex() == 1)
			return "btn btn-next-arrow next-disabled";
		else
			return "btn btn-next-arrow";
	}, this);

	function SwitchSortOrder() {
		if (this.SortOrder === "asc") {
			this.SortOrder = "desc";
		} else {
			this.SortOrder = "asc";
		}
		return this.SortOrder;
	}

	function SetTHClass(event, colName) {
		ClearSortImage();

		if (viewModel.SortOrder() === "asc") {
			$("#" + colName).children("span").addClass("asc");
		} else {
			$("#" + colName).children("span").addClass("desc");
		}
	}
	function SetOrder(event, ColName) {
		if (this.dataEmailOptOutList().length > 0) {
			if (this.ColName() === ColName) {
				this.SortOrder(SwitchSortOrder());
			} else {
				this.ColName(ColName);
				this.SortOrder("asc");
			}
			SetTHClass(event, ColName);
			if (ColName != "") {
				this.dataEmailOptOutList(SortByPropertyName(ko.utils.unwrapObservable(this.dataEmailOptOutList()), ColName, this.SortOrder()));
			}
		}
	}

	this.SetOrder = SetOrder; // Set to an knockout object

	// sort all items
	function SortByPropertyName(items, propertyName, sortOrder) {
		return items.sort(sortProperty(propertyName, sortOrder));
	}
	function sortProperty(property, sortOrder) {
		if (sortOrder == "asc")
			return function (a, b) {

				var number;
				if (isDateTime(a[property]) && isDateTime(b[property])) {
					return (parseDateTime(a[property]) < parseDateTime(b[property])) ? -1 : (parseDateTime(a[property]) > parseDateTime(b[property])) ? 1 : 0;
				} else {
					return (a[property].toLowerCase() < b[property].toLowerCase()) ? -1 : (a[property].toLowerCase() > b[property].toLowerCase()) ? 1 : 0;
				}
			}
		else
			return function (a, b) {
				var number;
				if (isDateTime(a[property]) && isDateTime(b[property])) {
					return (parseDateTime(a[property]) > parseDateTime(b[property])) ? -1 : (parseDateTime(a[property]) < parseDateTime(b[property])) ? 1 : 0;
				} else {
					return (a[property].toLowerCase() > b[property].toLowerCase()) ? -1 : (a[property].toLowerCase() < b[property].toLowerCase()) ? 1 : 0;
				}
			}
	}

};
ko.applyBindings(viewModel, document.getElementById("emailOptOutReportModel"));

// Set CurrentDatetime for it
$('#startDate').blur(function () {
	setTimeout(function () {
		if (!isDateUS($('#startDate').val())) {
			$('#startDate').val(getCurrentDate());
		}
	}, 1);
});

$('#endDate').blur(function () {
	setTimeout(function () {
		if (!isDateUS($('#endDate').val())) {
			$('#endDate').val(getCurrentDate());
		}
	}, 1);
});

//************ PRIVATE METHOD *************//
//Format percent output method
function FormatPercentOutput(percentInput) {
	if (percentInput != "0") {
		return percentInput + "%";
	} else {
		return percentInput;
	}
}

//Format percent output method
function FormatNumOutput(numberInput) {
	return "(" + numberInput + ")";
}

// Check datetime
function isDateTime(a) {
	var a = new Date(a);
	return ($.isNumeric(a.getTime()));
}

// Parse datetime to number
function parseDateTime(a) {
	var a = new Date(a);
	return (a.getTime());
}

function ClearSortImage() {
	$("div.title").parent().find(".sort_wrapper").children("span").removeClass("asc");
	$("div.title").parent().find(".sort_wrapper").children("span").removeClass("desc");
}
function hideProcess() {
	$('#popup-process').hide();
	$('.fancybox-skin').hide();
	$('#fancybox-overlay').hide();
}
// DOM ready
$(document).ready(function () {
	$('#pageIndex').removeClass("text-active");
	//$('#ui-datepicker-div').css("z-index", "99");
});